package com.jian.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.widget.ImageView;

public class BitmapUtils {

    private BitmapUtils() {

    }

    public Bitmap setCanves(Bitmap b) {

	Bitmap m = Bitmap.createBitmap(b.getWidth() + 50, b.getHeight() + 50,
		Config.ARGB_8888);
	Canvas c = new Canvas(m);
	c.drawColor(Color.GRAY);
	Paint p = new Paint();

	p.setColor(Color.RED);

	// 底层画圆，四个圆角边框
	Rect rct = new Rect(0, 0, m.getWidth(), m.getHeight());
	RectF rctf = new RectF(rct);
	c.drawRoundRect(rctf, 50f, 50f, p);
	c.drawBitmap(b, rct, rct, p);
	c.rotate(30, 0, m.getHeight());

	// 图片旋转，b为模板，左下角的坐标为选择点 15，为选择的角度
	Matrix ma = new Matrix();
	ma.setRotate(15, 0, m.getHeight());
	c.drawBitmap(b, ma, p);
	// 写文本文字
	p.setTextSize(20);
	p.setColor(Color.BLUE);
	c.drawText("这是测试", 50, 20, p);
	return m;
    }

    /**
     * 给图片画圆角 圆角半径20dip 白色背景
     * 
     * @param bitmap
     * @return
     */

    public static Bitmap drawRound(Bitmap bitmap) {

	Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
		bitmap.getHeight(), Config.ARGB_8888);
	Canvas canvas = new Canvas(output);
	final Paint paint = new Paint();
	paint.setColor(Color.WHITE);
	final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	final RectF rectF = new RectF(rect);
	paint.setAntiAlias(true);
	canvas.drawARGB(0, 0, 0, 0);
	canvas.drawRoundRect(rectF, 20.0f, 20.0f, paint);
	canvas.drawBitmap(bitmap, rect, rect, paint);
	return output;
    }

    /**
     * 获取一个指定大小的bitmap
     * 
     * @param bit
     * @param w
     *            指定宽
     * @param h
     *            指定高
     * @return
     */
    public static Bitmap getbitmap(Bitmap bit, int w, int h) {
	return Bitmap.createScaledBitmap(bit, w, h, true);
    }

    /**
     * 将Drawable转换成Bitmap
     * 
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
	Bitmap bitmap = Bitmap
		.createBitmap(
			drawable.getIntrinsicWidth(),
			drawable.getIntrinsicHeight(),
			drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565);
	Canvas canvas = new Canvas(bitmap);
	// canvas.setBitmap(bitmap);
	drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
		drawable.getIntrinsicHeight());
	drawable.draw(canvas);
	return bitmap;
    }

    /**
     * Bitmap to Bytes
     * 
     * @param bm
     * @return
     */
    public byte[] Bitmap2Bytes(Bitmap bm) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
	return baos.toByteArray();
    }

    /**
     * 将R.drawable.*转换成Bitmap
     * 
     * @param resId
     * @return
     */
    public static Bitmap decodeBitmap(Context c, int resId) {
	return BitmapFactory.decodeResource(c.getResources(), resId);
    }

    /**
     * 截取图片的中间的dstWidth*dstHeight的区域
     * 
     * @param bm
     * @return
     */
    public static Bitmap cropCenter(Bitmap bm, int dstWidth, int dstHeight) {
	int startWidth = (bm.getWidth() - dstWidth) / 2;
	int startHeight = ((bm.getHeight() - dstHeight) / 2);
	Rect src = new Rect(startWidth, startHeight, startWidth + dstWidth,
		startHeight + dstHeight);
	return dividePart(bm, src);
    }

    /**
     * 获取空图片的大小
     * 
     * @param path
     * @return
     */
    public static int[] getBitmapSize(String path) {

	Options opts = new Options();
	opts.inJustDecodeBounds = true; // 只解析图片大小
	BitmapFactory.decodeFile(path, opts);
	int[] wh = new int[2];
	wh[0] = opts.outWidth;
	wh[1] = opts.outHeight;
	return wh;

    }

    /**
     * 剪切图片
     * 
     * @param bmp
     *            被剪切的图片
     * @param src
     *            剪切的位置
     * @return 剪切后的图片
     */
    public static Bitmap dividePart(Bitmap bmp, Rect src) {
	int width = src.width();
	int height = src.height();
	Rect des = new Rect(0, 0, width, height);
	Bitmap croppedImage = Bitmap.createBitmap(width, height,
		Bitmap.Config.ARGB_8888);
	Canvas canvas = new Canvas(croppedImage);
	canvas.drawBitmap(bmp, src, des, null);
	return croppedImage;
    }

    /**
     * 加载大图片常用方式 按比例缩小，无法直接拉伸
     * 
     * @param path
     *            图片路径
     * @param maxx
     *            图片最大宽
     * @param maxy
     *            图片最大高
     * @return
     */

    public static Bitmap getbigImage(String path, int maxx, int maxy) {
	Options opts = new Options();
	opts.inJustDecodeBounds = true; // 只解析图片大小
	BitmapFactory.decodeFile(path, opts);
	double mw = opts.outWidth;
	double mh = opts.outHeight;
	int a = 1;
	if (maxx > mw && maxy > mh)
	    a = 1;
	else {
	    int aw = (int) (mw / maxx);
	    int ah = (int) (mh / maxy);
	    a = aw > ah ? ah : aw;
	}
	opts.inJustDecodeBounds = false;
	opts.inSampleSize = a;
	return BitmapFactory.decodeFile(path, opts);
    }

    /**
     * 获取指定大小的缩略图
     * 
     * @param bitmap
     * @param w
     * @param h
     * @return
     */

    public static Bitmap getThumbnail(Bitmap bitmap, int w, int h) {
	// 获取缩略图
	return ThumbnailUtils.extractThumbnail(bitmap, w, h);
    }

    /**
     * 把两张图合并成一张图
     * 
     * @param background
     *            底图
     * @param foreground
     *            上层的图
     * @return
     */

    public static Bitmap toConformBitmap(Bitmap background, Bitmap foreground) {
	if (background == null) {
	    return null;
	}

	int bgWidth = background.getWidth();
	int bgHeight = background.getHeight();
	// create the new blank bitmap 创建一个新的和SRC长度宽度一样的位图
	Bitmap newbmp = Bitmap
		.createBitmap(bgWidth, bgHeight, Config.ARGB_8888);
	Canvas cv = new Canvas(newbmp);
	// draw bg into
	cv.drawBitmap(background, 0, 0, null);// 在 0，0坐标开始画入bg
	// draw fg into
	cv.drawBitmap(foreground, 0, 0, null);// 在 0，0坐标开始画入fg ，可以从任意位置画入
	// save all clip
	cv.save(Canvas.ALL_SAVE_FLAG);// 保存
	// store
	cv.restore();// 存储
	return newbmp;
    }

    /**
     * 保存小图到本地
     * 
     * @param bitmap
     * @param TAGpath
     * @return
     */
    public static void saveBitmap(Bitmap bitmap, String TAGpath) {
	File file = new File(TAGpath);

	if (file.exists()) {
	    try {
		file.createNewFile();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	try {
	    FileOutputStream out = new FileOutputStream(file);
	    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
	    out.flush();
	    out.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * 获取iamgeview的图片
     * 
     * @param mView
     * @return
     */
    public static Bitmap getbitmap(ImageView mView) {
	mView.setDrawingCacheEnabled(true);
	Bitmap mBitmap = mView.getDrawingCache();
	mView.setDrawingCacheEnabled(false);
	return mBitmap;
    }

    /**
     * 保存控件内容
     * 
     * @param mView
     * @param path
     */
    public static void savebitmapbyview(ImageView mView, String path) {
	mView.setDrawingCacheEnabled(true);
	Bitmap mBitmap = mView.getDrawingCache();
	File file = new File(path);
	if (file.exists()) {
	    try {
		file.createNewFile();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	try {
	    FileOutputStream out = new FileOutputStream(file);
	    mBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
	    out.flush();
	    out.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
	mView.setDrawingCacheEnabled(false);
    }

    /**
     * 将bitmap对象保存为一个图片文件
     * 
     * @param bmp
     *            需要保存的bitmap对象
     * @param headPath
     *            保存的路径
     */
    public static boolean savebmp(Bitmap bmp, Uri uri) {
	boolean isUpload = false;
	File file = createFile(uri.getEncodedPath());
	try {
	    FileOutputStream out = new FileOutputStream(file);
	    bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
	    isUpload = true;
	} catch (Exception e) {
	    e.printStackTrace();
	    isUpload = false;
	}
	return isUpload;
    }

    /**
     * 根据路径创建文件
     * 
     * @param filePath
     *            需要创建的文件路径
     * @return 返回文件对象
     */
    public static File createFile(String filePath) {
	// String filePath = uri.getEncodedPath();
	String parentPath = filePath.substring(0, filePath.lastIndexOf("/"));
	File parentFile = new File(parentPath);
	if (!parentFile.exists()) {
	    parentFile.mkdirs();
	}
	File file = new File(filePath);
	if (file.exists()) {
	    file.delete();
	}
	try {
	    file.createNewFile();
	} catch (Exception e) {
	    e.printStackTrace();
	    return null;
	}
	return file;
    }

    /**
     * 根据Drawable或者图片路径得到图片的Bitmap对象
     * 
     * @param imageDrawable
     *            Drawable的值 不需要就传-1
     * @param imageFinePath
     *            图片路径 不需要就传null
     * @return 返回圆角处理后的图片
     */
    public static Bitmap getBitmap(Context mContext, int imageDrawable,
	    String imageFinePath) {
	if (imageDrawable != -1) {
	    InputStream input = mContext.getResources().openRawResource(
		    imageDrawable);
	    Bitmap bitmap = BitmapFactory.decodeStream(input);
	    return getRoundedCornerBitmap(bitmap);
	} else if (imageFinePath != null) {
	    try {
		InputStream input = new FileInputStream(new File(imageFinePath));
		return getRoundedCornerBitmap(BitmapFactory.decodeStream(input));
	    } catch (FileNotFoundException e) {
		e.printStackTrace();
	    }
	}
	return null;
    }

    /**
     * 图片圆角处理
     * 
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
	Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
		bitmap.getHeight(), Config.ARGB_8888);
	Canvas canvas = new Canvas(output);
	final int color = 0xff424242;
	final Paint paint = new Paint();
	final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	final RectF rectF = new RectF(rect);
	final float roundPx = 12;
	paint.setAntiAlias(true);
	canvas.drawARGB(0, 0, 0, 0);
	paint.setColor(color);
	canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
	paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	canvas.drawBitmap(bitmap, rect, rect, paint);
	return output;
    }

    /**
     * 根据传入的路径返回一个指定大小的图片
     * 
     * @param path
     * @param width
     * @param height
     * @return
     */
    public static Bitmap getBitmap(String path, int width, int height) {

	int[] bsize = getBitmapSize(path);
	Bitmap b;
	if (bsize[0] > width && bsize[1] > height) { // 防止图片太大。直接decodefile，内存不足
	    b = getbigImage(path, width, height);
	} else {
	    b = BitmapFactory.decodeFile(path);
	}
	b = getScaleBitmap(b, width, height);
	return getBitmap(b, width, height);
    }

    /**
     * 讲一个bitmap等比缩放到指定高度
     * 
     * @param b
     * @param width
     * @param height
     * @return
     */

    public static Bitmap getBitmap(Bitmap b, int width, int height) {

	if (b.getWidth() != width) {
	    return getZoomBitmap(b, width, height);// 缩放图片到等比大小
	} else {
	    return b;
	}
    }

    /**
     * 根据传入的宽/高，从当前bitmap中截取出一个等比例的bitmap
     * 
     * @param b
     * @param width
     * @param height
     * @return
     */
    public static Bitmap getScaleBitmap(Bitmap b, int width, int height) {

	double msize = (width + 0.0) / height;
	double currensize = (b.getWidth() + 0.0) / (b.getHeight() + 0.0);
	// 宽/高 >msize(16/9);
	if (currensize > msize) {
	    // 裁剪宽，，高不变
	    int mw = (int) (b.getHeight() * msize);
	    b = cropCenter(b, mw, b.getHeight());
	} else if (currensize < msize) {
	    // 宽不变，裁剪高
	    int mh = (b.getWidth() * height) / width;
	    b = cropCenter(b, b.getWidth(), mh);
	}
	return getBitmap(b, width, height);

    }

    /**
     * 缩放bitmap到指定的大小 ,原图宽高比例/与传入的width:height 比例可不同
     * 
     * @param bitmap
     * @param width
     * @param height
     * @return
     */
    public static Bitmap getZoomBitmap(Bitmap bitmap, int width, int height) {
	double sw = (width + 0.0) / bitmap.getWidth();
	double sh = (height + 0.0) / bitmap.getHeight();
	/* 设置宽高各自应放大缩小的比例 */
	float scaleWidth = (float) (1 * sw);
	float scaleHeight = (float) (1 * sh);
	Matrix matrix = new Matrix();
	matrix.postScale(scaleWidth, scaleHeight);
	return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
		bitmap.getHeight(), matrix, true);
    }

}
